import logging

from fastapi import APIRouter, Query
from tortoise.expressions import Q
from app.controllers.blog import BlogController, blog_controller
from app.controllers.category import CategoryController, category_controller
from app.core.dependency import DependPermission
from app.schemas.base import Fail, Success, SuccessExtra
from app.schemas.blogs import *

router = APIRouter()

order_options = [{
    'label': "图片时间-降序",
    'value': 'meta_time_desc',
    'order': '-time'
}, {
    'label': "图片时间-升序",
    'value': 'meta_time_asc',
    'order': 'time'
}, {
    'label': "图片创建时间-降序",
    'value': 'created_at_desc',
    'order': '-created_at'
}, {
    'label': "图片创建时间-升序",
    'value': 'created_at_asc',
    'order': 'created_at'
}, {
    'label': "图片更新时间-降序",
    'value': 'updated_at_desc',
    'order': '-updated_at'
}, {
    'label': "图片更新时间-升序",
    'value': 'updated_at_asc',
    'order': 'updated_at'
}]


@router.post("/list", summary="查询图片列表")
async def list_blog(query: BlogQuery):
    q = Q()
    if query.title:
        q &= Q(title__icontains=query.title)
    if query.desc:
        q &= Q(desc__icontains=query.desc)
    if query.location:
        q &= Q(location__icontains=query.location)
    if query.categories:
        q &= Q(categories__in=query.categories)
    order = None
    for t in order_options:
        if t['value'] == query.order_option:
            order = t['order']
            break
    if order:
        total, blog_objs = await blog_controller.list(
            page=query.page, page_size=query.page_size, search=q, order=order)
    else:
        total, blog_objs = await blog_controller.list(
            page=query.page, page_size=query.page_size, search=q)
    data = [await obj.to_dict() for obj in blog_objs]

    # for blog in data:
    #     blog['formatted_categories'] = blog['categories']
    #     blog['categories'] = [
    #         item['id'] for item in blog['formatted_categories']
    #     ]
    return SuccessExtra(data=data,
                        total=total,
                        page=query.page,
                        page_size=query.page_size)
